package cn.sightsnow.zh.service;

import cn.sightsnow.zh.util.HttpUtil;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class AccessTokenService {
    @Value("${easyDL.accessTokenUrl}")
    String accessTokenUrl;
    @Value("${easyDL.key}")
    String easyDlKey;
    @Value("${easyDL.secret}")
    String easyDlSecret;
    private static final long ACCESS_TOKEN_EXPIRATION = 86400; // 86400秒，即1天

    // 创建一个 Cache 实例，设置过期时间
    private final Cache<String, String> accessTokenCache = CacheBuilder.newBuilder()
            .expireAfterWrite(ACCESS_TOKEN_EXPIRATION, TimeUnit.SECONDS)
            .build();

    public String getAccessToken() throws Exception {
        // 尝试从缓存中获取 accessToken
        String accessToken = accessTokenCache.getIfPresent("accessToken");
        if (accessToken == null) {
            // 如果缓存中不存在，则重新获取
            String param = "grant_type=client_credentials&client_id=" + easyDlKey + "&client_secret=" + easyDlSecret;
            String response = HttpUtil.post(accessTokenUrl, "", "application/x-www-form-urlencoded", param);
            JsonObject jsonObject = JsonParser.parseString(response).getAsJsonObject();
            accessToken = jsonObject.get("access_token").getAsString();
            // 将新获取的 accessToken 存入缓存
            accessTokenCache.put("accessToken", accessToken);
        }
        return accessToken;
    }
}